package com.yiduo.outpost.core.feign.insterceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.yiduo.outpost.core.model.constant.SecurityConstant;
import java.util.Collection;
import java.util.Objects;

public class OpenFeignUserTokenInterceptor implements RequestInterceptor {


    public OpenFeignUserTokenInterceptor() {
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && !Objects.nonNull(authentication.getCredentials())) {
            Collection<String> token = requestTemplate.headers().get(SecurityConstant.AUTHORIZATION_HEADER);
            if (Objects.isNull(token) || token.isEmpty()) {
                requestTemplate.header(SecurityConstant.AUTHORIZATION_HEADER,
                    SecurityConstant.BEARER_PREFIX + authentication.getCredentials());
            }
        }
    }
}